package com.nofx.mydemo;

import com.nofx.mydemo.entity.User;
import com.nofx.mydemo.publisher.CustomSpringEventPublisher;
import com.nofx.mydemo.service.IGitHubLookupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author yanyuchi
 * @date 2021-04-27 21:22
 */
@Slf4j
@Component
public class AppRunner implements CommandLineRunner {

    private final IGitHubLookupService gitHubLookupService;
    private final CustomSpringEventPublisher publisher;

    public AppRunner(IGitHubLookupService gitHubLookupService,CustomSpringEventPublisher publisher) {
        this.gitHubLookupService = gitHubLookupService;
        this.publisher = publisher;
    }

    @Override
    public void run(String... args) throws Exception {
        // Start the clock
        long start = System.currentTimeMillis();

        // Kick of multiple, asynchronous lookups
        CompletableFuture<User> page1 = gitHubLookupService.findUser("PivotalSoftware");
        CompletableFuture<User> page2 = gitHubLookupService.findUser("CloudFoundry");
        CompletableFuture<User> page3 = gitHubLookupService.findUser("Spring-Projects");

        // Wait until they are all done
        CompletableFuture.allOf(page1,page2,page3).join();

        // Print results, including elapsed time
        log.info("Elapsed time: " + (System.currentTimeMillis() - start));
        log.info("--> " + page1.get());
        log.info("--> " + page2.get());
        log.info("--> " + page3.get());


        log.info("========");
        publisher.publishCustomEvent(" MSG-ONE");
        publisher.publishCustomEvent(" MSG-TWO");




    }
}
